import 'package:flutter/material.dart';
import 'package:safety_platform/models/received_notification.dart';
import 'package:safety_platform/components/search.dart';
import 'package:safety_platform/components/loading.dart';
import 'package:safety_platform/bloc/notification/notification.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:safety_platform/utils.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:safety_platform/pages/notification/notification_detail_page.dart';

class NotificationPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _NotificationState();
}

typedef OnPreviewNotifcationCallback = Function(ReceivedNotification rn);

class ReceivedNotificationListWidget extends StatefulWidget {
  final List<ReceivedNotification> data;
  final Function onRefresh;
  final Function loadMore;
  final OnPreviewNotifcationCallback onPress;
  // final Function<ReceivedNotification> onPress ;
  const ReceivedNotificationListWidget(this.data, this.onRefresh,
      {this.loadMore, this.onPress});
  @override
  State<StatefulWidget> createState() {
    return _ReceivedNotificationListState();
  }
}

class _ReceivedNotificationListState
    extends State<ReceivedNotificationListWidget> {
  GlobalKey<RefreshHeaderState>
      _headerKey; //= new GlobalKey<RefreshHeaderState>();
  GlobalKey<RefreshFooterState> _footerKey;
  GlobalKey<EasyRefreshState> _easyRefreshKey =
      new GlobalKey<EasyRefreshState>();

  _ReceivedNotificationListState();

  @override
  void initState() {
    super.initState();
    print('initState');
    _headerKey = GlobalKey();
    _footerKey = GlobalKey();
    // _controller = RefreshController();
  }

  @override
  void didUpdateWidget(ReceivedNotificationListWidget oldWidget) {
    print('didUpdateWidget');
    super.didUpdateWidget(oldWidget);
    if (oldWidget != widget) {
      if (_easyRefreshKey != null) {
        if (_easyRefreshKey.currentState.isRefreshing) {
          _easyRefreshKey.currentState.callRefreshFinish();
        }
        _easyRefreshKey.currentState.callLoadMoreFinish();
      }
      // _headerKey.currentState.c
      // _headerKey.currentState.
      // if (_controller.isRefresh(true)) {
      // _controller.sendBack(true, RefreshStatus.completed);
    }
  }

  @override
  Widget build(BuildContext context) {
    print('List Build');

    return _buildBody(context);
  }

  @override
  void dispose() {
    // _controller = null;
    
    super.dispose();
  }

  String _transStatus(ReceivedNotification notification) {
    if (notification.signed) {
      return '已签阅';
    } else {
      return '未签阅';
    }
  }

  Widget _buildBody(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Search(null),
          Expanded(child: _buildListWidget()),
        ],
      ),
    );
  }

  Widget _buildItem(BuildContext context, int index) {
    ReceivedNotification notification = widget.data[index];

    return GestureDetector(
      onTap: () {
        // Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
        // return NotificationDetailPage(notification);
        // });
        // widget.onPress(notification);
        Navigator.of(context).push(MaterialPageRoute(builder: (_) {
          NotificationOperationState state =
              NotificationOperationState.fromData(notification);

          // return  ReceivedNotificationWidget(notification);
          return NotificationDetailPage(state);
        })).then((rn) {
          if (rn != null) {
            NotificationBloc _bloc = BlocProvider.of<NotificationBloc>(context);
            print('更新后的通知 $rn');
            _bloc.dispatch(NotificationUpdatedEvent(rn));
          }
          ;
        });
      },
      child: Container(
        height: 72,
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                bottom: BorderSide(
              color: Color.fromARGB(255, 241, 241, 241),
              width: 1,
            ))),
        // padding: EdgeInsets.all(16),
        child: Row(
          children: <Widget>[
            Container(
                color: Colors.blue,
                padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _transStatus(notification),
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                      ),
                      Padding(
                          padding: EdgeInsets.fromLTRB(0, 6, 0, 0),
                          child: Text(
                              formatDate(
                                  notification.notification.datePublished,
                                  format: 'MM-dd'),
                              style: TextStyle(color: Colors.white))),
                    ])),
            Expanded(
              child: Container(
                // color: Colors.red,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                        child: Text(
                      '${notification.notification.title}',
                      // '关于督促生产经营单位建立健全安全生产档案的通知',
                      style: notification.read
                          ? TextStyle(color: Colors.black54)
                          : null,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    )),
                    Container(
                      decoration: BoxDecoration(
                          // color: Colors.blue,
                          borderRadius: BorderRadius.circular(4.0)),
                      // padding: EdgeInsets.all(4),
                      child: Text(
                        '政策通知',
                        style: TextStyle(color: Colors.grey, fontSize: 12),
                      ),
                    )
                  ],
                ),
                margin: EdgeInsets.only(top: 4),
                padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<Null> _onRefresh() {
    widget.onRefresh();
    return Future.value(null);
  }

  Future<Null> _loadMore() {
    if (widget.loadMore != null) {
      widget.loadMore();
    } else {
      _easyRefreshKey.currentState.callLoadMoreFinish();
    }
    return Future.value(null);
  }

  Widget _buildListWidget() {
    Widget widget1 = EasyRefresh(
        refreshHeader: ClassicsHeader(
          key: _headerKey,
          bgColor: Colors.white70,
          textColor: Colors.black54,
          refreshText: '下拉刷新',
          refreshReadyText: '释放即开始刷新',
          refreshingText: '刷新中，请稍候..',
          refreshedText: '刷新完成',
        ),
        refreshFooter: ClassicsFooter(
          key: _footerKey,
          loadText: '上拉加载更多',
          noMoreText: '没有更多数据了',
          loadReadyText: '释放加载更多',
          loadingText: '正在加载，请稍候..',
          loadedText: '加载完成',
          bgColor: Colors.white70,
          // bgColor: Theme.of(context).backgroundColor,
          textColor: Colors.black54,
        ),
        key: _easyRefreshKey,
        autoControl: false,
        onRefresh: _onRefresh,
        loadMore: _loadMore,
        // enablePullDown: true,
        // enablePullUp: true,
        // onRefresh: _onRefresh,
        // controller: _controller,
        // footerConfig: LoadConfig(
        // bottomWhenBuild: false,
        // ),
        // headerBuilder: (BuildContext context, int mode) {
        //   return ClassicIndicator(
        //     mode: mode,
        //     refreshingText: '正在刷新',
        //     completeText: '刷新成功',
        //     idleText: '下拉刷新',
        //     releaseText: '下拉刷新',
        //   );
        // },
        // onOffsetChange: _onOffsetCallback,÷
        child: new ListView.builder(
          itemCount: widget.data.length,
          itemBuilder: _buildItem,
        ));
    return widget1;
    // _controller.sendBack(true, RefreshStatus.completed);
    // return Refresh(
    //  onFooterRefresh: null,
    // onHeaderRefresh: _loadData,
    //child: ListView.builder(
    // itemCount: this.data.length,
    //itemBuilder: _buildItem,
    // ),
    //);
  }
}

class _NotificationState extends State<NotificationPage> {
  List<ReceivedNotification> dataList = List();

  NotificationBloc _bloc;
  @override
  void initState() {
    super.initState();
    _bloc = NotificationBloc();
    _bloc.dispatch(NotificationStartupEvent());
    print('index=> initState');
    // _loadData();
  }

  @override
  void dispose() {
    _bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<NotificationBloc>(
      bloc: _bloc,
      child: BlocBuilder(
          bloc: _bloc,
          builder: (BuildContext context, NotificationState state) {
            print('index build => $state');
            return Scaffold(
              resizeToAvoidBottomPadding: false,
              appBar: AppBar(
                title: new Text('通知列表'),
                elevation: 0,
                centerTitle: true, //设置标题是否局中
              ),
              body: _body(state),
            );
          }),
    );
  }

  // Future<Null> _onRefresh() {
  //   _bloc.dispatchAndWait(NotficationRefreshEvent()).then((_) {
  //     Future.value(null);
  //   });
  // }

  _body(NotificationState state) {
    // if (state is NotificationDetail) {
    //   return NotificationDetailPage(state.data);
    // }
    // if (state is NotificationLoadingState) {
    //   return Loading();
    // }
    // if (state is NotificationDataIsEmpty) {
    //   return Center(
    //     child: Text('没有数据'),
    //   );
    // }
    if (state is NotificationLoadingState) {
      return Loading();
    }
    if (state is NotificationState) {
      return ReceivedNotificationListWidget(state.data,
          () => _bloc.dispatch(NotficationRefreshEvent(throwLoadState: false)),
          onPress: (_) {},
          loadMore: state.hasMore()
              ? () => _bloc.dispatch(NotficationRefreshEvent(
                    loadMore: true,
                    throwLoadState: false,
                    page: state.nextPage,
                  ))
              : null);
    }
    return Container();
  }

  // Future<Null> _onFooterRefresh() async {
  //   if (_next != null) {
  //     ReceivedNotificationPage page = await loadReceivedNotification(
  //         page: this._page + 1, pageSize: this._pageSize);

  //     dataList.addAll(page.results);
  //     setState(() {
  //       _count = page.count;
  //       _next = page.next;
  //     });
  //   }
  //   return Future.value(null);
  // }

  // Future<Null> _onHeaderRefresh() async {
  //   ReceivedNotificationPage page =
  //       await loadReceivedNotification(page: 1, pageSize: this._pageSize);

  //   dataList.clear();
  //   dataList.addAll(page.results);

  //   setState(() {
  //     _status = 'done';
  //     _next = page.next;
  //     _count = page.count;
  //   });
  //   return Future.value(null);
  // }

  // _buildListWidget() {
  //   return Refresh(
  //     onFooterRefresh: _onFooterRefresh,
  //     onHeaderRefresh: _onHeaderRefresh,
  //     child: ListView.builder(
  //       itemCount: this.dataList.length,
  //       itemBuilder: _buildItem,
  //     ),
  //   );
  // }

  // return FutureBuilder<ReceivedNotificationPage>(
  //     future: _loadData(),
  //     builder: (BuildContext context,
  //         AsyncSnapshot<ReceivedNotificationPage> snapshort) {
  //       ConnectionState state = snapshort.connectionState;
  //       switch (state) {
  //         case ConnectionState.active:
  //         case ConnectionState.none:
  //         case ConnectionState.waiting:
  //           {
  //             print(state);
  //             return Text('加载中');
  //           }
  //         case ConnectionState.done:
  //           {
  //             ReceivedNotificationPage page = snapshort.data;
  //             // this._count = page.count;
  //             // this._next = page.next;
  //             // this.dataList.addAll(page.results);
  //             return Text('ok');
  //           }
  //       }
  //     });
}
